﻿using Microsoft.Extensions.Logging;

namespace GMS.NET.Web.Components.Shared.Global.Misc.Logger
{
    public class LoggerExtensions : ILogger
    {
        private readonly string? _logFileBasePath;
        public LoggerExtensions(string? logFileBasePath)
        {
            _logFileBasePath = logFileBasePath;
        }

        private static readonly object _lock = new object();
        public IDisposable BeginScope<TState>(TState state)
        {
            return null!;
        }
        public bool IsEnabled(LogLevel logLevel)
        {
            return true;
        }
        public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
        {
            if (!IsEnabled(logLevel))
            {
                return;
            }

            string logMessage = formatter(state, exception);
            string formattedLogEntry = $"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [{logLevel}] {logMessage}";

            lock (_lock)
            {
                try
                {
                    using (StreamWriter writer = File.AppendText(_logFileBasePath!))
                    {
                        writer.WriteLine(formattedLogEntry);
                    }
                }
                catch (Exception ex)
                {
                    using (StreamWriter writer = File.AppendText(_logFileBasePath!))
                    {
                        writer.WriteLine($"{DateTime.Now:yyyy-MM-dd HH:mm:ss} [Error] 写入日志错误 {ex.Message}{Environment.NewLine}");
                    }
                }
            }
        }
    }
}
